//
//  SimpleStore.swift
//  GerritHermes
//
//  Created by J.Zhou on 2020/2/10.
//  Copyright © 2020 周剑. All rights reserved.
//

import Foundation
import SQLite

final class SimpleStore {
    static var db: Connection { KVTableHelper.shared.db }
    static let table = Table("SimpleStore")

    static var idColumn: Expression<Int> { Expression<Int>("id") }
    static var keyColumn: Expression<String> { Expression<String>("key") }
    static var dataColumn: Expression<Blob> { Expression<Blob>("data") }

    static var encoder: JSONEncoder { return KVTableHelper.shared.encoder }
    static var decoder: JSONDecoder { return KVTableHelper.shared.decoder }

}

extension SimpleStore {

    static func createIfNotExsists() throws {
        try db.run(table.create(ifNotExists: true) { t in
            t.column(idColumn, primaryKey: .autoincrement)
            t.column(keyColumn, unique: true)
            t.column(dataColumn)
        })
    }

    static func set<T: Encodable>(_ value: T, for key: String) throws {
        let data = try encoder.encode(value)
        try db.run(table.insert(or: .replace, keyColumn <- key, dataColumn <- data))
    }

    static func delete(key: String) throws {
        let table = self.table.filter(keyColumn == key)
        try db.run(table.delete())
    }

    static func deleteAll() throws {
        try db.run(table.delete())
    }

    static func object<T: Decodable>(for key: String) throws -> T? {
        let table = self.table.filter(keyColumn == key)
        if let row = try db.pluck(table) {
            return try? decoder.decode(T.self, from: row[dataColumn])
        } else {
            return nil
        }
    }
}
